//
//  DTDeviceAudioAction.m
//  PersonalManager
//
//  Created by user on 16/8/17.
//  Copyright © 2016年 Haiyun.Qian. All rights reserved.
//

#import "DTDeviceAudioAction.h"
#import <AVFoundation/AVFoundation.h>
#import <UIKit/UIKit.h>

@interface DTDeviceAudioAction ()<AVAudioRecorderDelegate,AVAudioPlayerDelegate,NSURLSessionDownloadDelegate>

@property(nonatomic,strong) AVAudioRecorder *recorder;

/** 存储录音文件名字 */
@property(nonatomic,strong) NSString *recordAudioName;

//录音文件路径
@property(nonatomic,strong) NSString *recordPath;

/** 60秒定时器 */
@property(nonatomic,strong) NSTimer *timer;
/** 记录60秒的时间,会自增 */
@property(nonatomic,assign) NSTimeInterval recordSecond;

/** 音频播放器 */
@property(nonatomic,strong) AVAudioPlayer *audioPlayer;

/** 存储音频当前的播放进度 */
@property(nonatomic,assign) NSTimeInterval nowAudioPlayTime;

/** 网络上传和下载 */
@property(nonatomic,strong) NSURLSessionDownloadTask *downloadTask;

/** 用于接收下载的数据 */
@property(nonatomic,strong) NSMutableData *audioData;

/** 下载音频的大小 */
@property(nonatomic,assign) long long audioLength;

/** 写文件操作柄 */
@property(nonatomic,strong) NSFileHandle *writeHandle;

@property(nonatomic,strong) NSURLSession *session;

@end

@implementation DTDeviceAudioAction

/** 定义录音文件的扩展名,为以后查找判断是不是我的录音文件用 */
static NSString *recordAudioExtensionName = @"aac";

//懒加载
- (NSString *)recordPath {
    if (!_recordPath) {
        NSString *cacheRecordPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"recordAudio"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:cacheRecordPath]) {
            if([[NSFileManager defaultManager] createDirectoryAtPath:cacheRecordPath withIntermediateDirectories:YES attributes:nil error:nil]){
                NSLog(@"创建~/recordAudio 目录成功");
            }
        }
        _recordPath = cacheRecordPath;
    }
    return _recordPath;
}
- (NSURLSession *)session{
    if (!_session) {
        _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}


- (void)startRecord {
    
    if(self.recorder){
        return;
    }
    
    self.recordSecond = 0.0;
    

    //设置定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(stopRecordAudio) userInfo:nil repeats:YES];
    [self.timer fire];
    
    self.recordAudioName = [NSString stringWithFormat:@"%d.%@",(int)[NSDate date].timeIntervalSince1970,recordAudioExtensionName];
    NSString *path = [self.recordPath stringByAppendingPathComponent:self.recordAudioName];
    NSError *error = nil;
    
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending)
    {
        //7.0第一次运行会提示，是否允许使用麦克风
        AVAudioSession *session = [AVAudioSession sharedInstance];
        NSError *sessionError;
        //AVAudioSessionCategoryPlayAndRecord用于录音和播放
        [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
        if(session == nil){
           [self.command failedResponse:-1 andmessage:@"创建audioSession失败"];
           return;
        }else{
            [session setActive:YES error:nil];
        }
    }
    
    //录音机初始化
    /*
     1.AVNumberOfChannelsKey 通道数 通常为双声道 值2
     2.AVSampleRateKey 采样率 单位HZ 通常设置成44100 也就是44.1k
     3.AVLinearPCMBitDepthKey 比特率 8 16 24 32
     4.AVEncoderAudioQualityKey 声音质量
     ① AVAudioQualityMin  = 0, 最小的质量
     ② AVAudioQualityLow  = 0x20, 比较低的质量
     ③ AVAudioQualityMedium = 0x40, 中间的质量
     ④ AVAudioQualityHigh  = 0x60,高的质量
     ⑤ AVAudioQualityMax  = 0x7F 最好的质量
     5.AVEncoderBitRateKey 音频编码的比特率 单位Kbps 传输的速率 一般设置128000 也就是128kbps
     
     */
    NSDictionary *setting = [[NSDictionary alloc] initWithObjectsAndKeys:
                             [NSNumber numberWithInt:kAudioFormatMPEG4AAC],AVFormatIDKey,
                             [NSNumber numberWithInt:1000.0],AVSampleRateKey,
                             [NSNumber numberWithInt:2],AVNumberOfChannelsKey,
                             [NSNumber numberWithInt:8],AVLinearPCMBitDepthKey,
                             [NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,
                             [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,
                             nil];
    self.recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL URLWithString:path] settings:setting error:&error];
    if (self.recorder) {
        self.recorder.meteringEnabled = YES;
        self.recorder.delegate = self;
        [self.recorder prepareToRecord];
        [self.recorder record];
    }

    
}

- (void)stopRecord {
    if (!self.recorder) {
        return;
    }
    if (!self.recorder.isRecording) {
        return;
    }
    [self.recorder stop];
    self.recorder = nil;
    [self.timer invalidate];//注销,设为无效
    self.timer = nil;
    
}

//定时器触发
-(void) stopRecordAudio {
    self.recordSecond += 1;
    self.command.controller.navigationItem.title = [NSString stringWithFormat:@"录音中...%.0lfs",self.recordSecond];
    if (self.recordSecond >= 60) {
        [self stopRecord];
    }
}

- (void)onRecordEnd {
    NSString *string = @"";
    if (!self.timer) {
        string = @"定时器未开启";
    }else {
        string = @"定时器已开启";
    }
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:string, @"设置时", nil];
    [self.command successRessponse:dic];
}

- (void)play {
    self.audioPlayer = nil;
    NSString *path = [self.recordPath stringByAppendingPathComponent:self.recordAudioName];
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:path] error:nil];
    if (self.audioPlayer == nil)
    {
        [self.command failedResponse:-1 andmessage:@"无音频文件"];
    }
    else {
        self.audioPlayer.delegate = self;
        //音量
        self.audioPlayer.volume = 1.0;
        //循环次数
        //self.audioPlayer.numberOfLoops = 0;//不循环
        //从哪里开始播放
        //self.audioPlayer.currentTime = 0;
        
        //声道
        //self.audioPlayer.pan = 0.0;
        //获取持续时间

        //播放
        [self.audioPlayer prepareToPlay];
        if (!self.audioPlayer.isPlaying) {
            [self.audioPlayer play];
        }
    }
}

- (void)pause {
    if (!self.audioPlayer) {
        return;
    }
    if (self.audioPlayer.isPlaying) {
        self.nowAudioPlayTime = self.audioPlayer.currentTime;
        [self.audioPlayer pause];
    }
}

- (void)resume {
    if (!self.audioPlayer) {
        return;
    }
    if (self.audioPlayer.isPlaying) {
        return;
    }
    self.audioPlayer.currentTime = self.nowAudioPlayTime;
    [self.audioPlayer play];
}

- (void)stop {
    if (!self.audioPlayer) {
        return;
    }
    [self.audioPlayer stop];
    self.audioPlayer = nil;
}

- (void)onPlayEnd{
    if (!self.audioPlayer) {
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"播放已结束", self.recordAudioName, nil];
        [self.command successRessponse:dic];
    }
}

- (void)download {
    //存储网络需要下载的音频的url
    NSURL *audioURL = [NSURL URLWithString:@"http://sc1.111ttt.com/2016/1/08/18/201181848434.mp3"];
    NSString *str = audioURL.absoluteString;
    str = [self codeToSuggestName:str];
    NSArray *pathArray = [[NSFileManager defaultManager] subpathsAtPath:self.recordPath];
    for (NSString *alsoDownload in pathArray) {
        if ([alsoDownload isEqualToString:str]) {
            self.recordAudioName = alsoDownload;
            [self.command failedResponse:0 andmessage:@"已下载,无需重复下载"];
            return;
        }
    }
    self.downloadTask = [self.session downloadTaskWithURL:audioURL];
    [self.downloadTask resume];
    
}

- (void)translateVoice {
    
}

//将url的尾缀返回
- (NSString *)codeToSuggestName:(NSString *)str {
    //以'/'分割字符串,得到在'/'中间的一组字符串
    NSArray *array = [str componentsSeparatedByString:@"/"];
    /*
    for (NSString *subStr in array) {
        NSLog(@"============== %@",subStr);
    }
     */
    NSString *iWantString = [array objectAtIndex:array.count - 1];
    return iWantString;
}


#pragma mark - AVAudioRecorderDelegate
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
    [self.command failedResponse:0 andmessage:@"录音结束"];
    NSFileManager *manager = [NSFileManager defaultManager];
    //获取当前文件下的所有子文件
    NSArray *pathList = [manager subpathsAtPath:self.recordPath];
//    NSMutableArray *audioPathList = [NSMutableArray array];
    //遍历子文件
    for (NSString *audioPath in pathList) {
        //判断是否为录音文件
        if ([audioPath.pathExtension isEqualToString:recordAudioExtensionName]) {
            //文件路径放进数组
            if ([audioPath isEqualToString:self.recordAudioName]) {
                NSString *durationString = [NSString stringWithFormat:@"%.0lfs",self.recordSecond];
                NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:audioPath, @"录制文件名",durationString,@"时长", nil];
                [self.command successRessponse:dic];
                self.command.controller.navigationItem.title = @"";
                return;
            }
        }
    }
}

#pragma mark - AVAudioPlayerDelegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    //播放结束时执行代码
    NSTimeInterval duration = self.audioPlayer.duration;
    NSInteger time = (NSInteger)duration;
    NSNumber *minute = ((time / 60) > 0) ? @(time / 60) : nil;
    NSNumber *second = @(time % 60);
    NSString *timeStr = nil;
    if (minute == nil) {
        timeStr = [NSString stringWithFormat:@"%02lds",(long)second.integerValue];
    }else{
        timeStr = [NSString stringWithFormat:@"%02ld:%02ld",(long)minute.integerValue,(long)second.integerValue];
    }
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:timeStr, @"播放结束,时长为", nil];
    [self.command successRessponse:dic];
    player = nil;
}

- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player {
    //开始打断播放,执行代码
    NSLog(@"开始打断");
}

- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player {
    //结束打断,执行代码
    NSLog(@"结束打断");
}

#pragma mark - NSURLSessionDownloadDelegate

//下载成功,我们需要更改下载文件的存储位置时调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    NSString *audioPath = [self.recordPath stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    self.recordAudioName = downloadTask.response.suggestedFilename;
    NSError *err = nil;
    [[NSFileManager defaultManager] moveItemAtPath:location.path toPath:audioPath error:&err];
    if (err) {
        NSString *string = [NSString stringWithFormat:@"移动文件失败"];
        [self.command failedResponse:-1 andmessage:string];
        //NSLog(@"%@",[err description]);
    }else {
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"移动成功", @"文件", nil];
        [self.command successRessponse:dic];
    }
    
    
}

//无论是否下载成功都会调用此方法
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    //error == nil,表示成功
    
}

//当下载从中断重新开始时,会调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes {
    
}

//下载进度变化时会调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    float process = (float)totalBytesWritten / totalBytesExpectedToWrite * 100;
    NSString *str = @"%";
    NSString *processStr = [NSString stringWithFormat:@"===== 已下载%.1f%@",process,str];
    [self.command failedResponse:0 andmessage:processStr];
}



@end
